<?php

namespace yunj\core;

use think\console\Command as ThinkCommand;
use think\console\Input;
use think\console\Output;

abstract class Command extends ThinkCommand {

    public function run(Input $input, Output $output): int {
        // 绑定输入输出对象，供给其他服务调用（如：日志记录）
        app()->bind('commandInput', function () use ($input) {
            return $input;
        });
        app()->bind('commandOutput', function () use ($output) {
            return $output;
        });
        return parent::run($input, $output);
    }

    // 问题
    public function confirm(string $question) {
        // 输出一个提示
        $text = sprintf('%s [Y/N]: ', $question);
        fwrite(STDOUT, $text);
        $res = trim(fgets(STDIN));
        if (!$res) return false;
        $res = strtolower($res);
        // 接受输入
        return $res === 'y' || $res === 'yes';
    }

    // 询问
    public function ask(string $desc) {
        // 输出一个提示
        $text = sprintf('%s: ', $desc);
        fwrite(STDOUT, $text);
        // 接受输入
        return trim(fgets(STDIN));
    }

    // 跳过消息
    public function skip(string $message, bool $nextLine = true) {
        $text = sprintf("\033[%smSkip! %s\033[%sm", '34', $message, '39') . ($nextLine ? "\r\n" : '');
        fwrite(STDOUT, $text);
    }

    // 常规消息
    public function info(string $message, bool $nextLine = true) {
        $text = $message . ($nextLine ? "\r\n" : '');
        fwrite(STDOUT, $text);
    }

    // 成功消息
    public function success(string $message = '', bool $nextLine = false, bool $prefix = true) {
        $message = $message ?: $this->getDescription();
        if ($prefix) $message = "Success! " . $message;
        $text = sprintf("\033[%sm%s\033[%sm", '32', $message, '39') . ($nextLine ? "\r\n" : '');
        fwrite(STDOUT, $text);
    }

    // 错误消息
    public function error($err, bool $nextLine = false) {
        if ($err instanceof \Throwable) $err = exception_to_str($err);
        $text = sprintf("\033[%smError: %s\033[%sm", '31', $err, '39') . ($nextLine ? "\r\n" : '');
        fwrite(STDOUT, $text);
    }

    // 警告消息
    public function warning(string $message, bool $nextLine = true) {
        $text = sprintf("\033[%smWarning! %s\033[%sm", '33', $message, '39') . ($nextLine ? "\r\n" : '');
        fwrite(STDOUT, $text);
    }

}